<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use App\Models\Traits\SeckillProductCacheTrait;
use Exception;

class SeckillProduct extends Model
{
    use HasFactory,SeckillProductCacheTrait;
    
    protected $guarded = ['id'];
    

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function scopeAvailable(Builder $builder): Builder
    {
        return $builder->where('is_open', true)->orderByDesc('is_new');
    }


     //批量更新
    protected function updateBatch($multipleData = [])
    {
        $tableColumn = Schema::getColumnListing($this->getTable());
        try {
            if (empty($multipleData)) {
                throw new Exception("数据不能为空");
            }

            $tableName = $this->getTable(); // 表名
            $firstRow = current($multipleData);
            $dataColumn = array_keys($firstRow);
            // 默认以id为条件更新，如果没有ID则以第一个字段为条件
            $referenceColumn = isset($firstRow['id']) ? 'id' : current($dataColumn);
            unset($dataColumn[0]);
            // 拼接sql语句
            $updateColumn = array_intersect($dataColumn, $tableColumn);
            $updateSql = "UPDATE " . $tableName . " SET ";
            $sets  = [];
            $bindings = [];
            foreach ($updateColumn as $uColumn) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ($multipleData as $data) {
                    $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                    $bindings[] = $data[$referenceColumn];
                    $bindings[] = $data[$uColumn];
                }
                $setSql .= "ELSE `" . $uColumn . "` END ";
                $sets[] = $setSql;
            }
            $updateSql .= implode(', ', $sets);
            $whereIn = collect($multipleData)->pluck($referenceColumn)->values()->all();
            $bindings = array_merge($bindings, $whereIn);
            $whereIn = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
            // 传入预处理sql语句和对应绑定数据
            return DB::update($updateSql, $bindings);
        } catch (Exception $e) {
            return false;
        }
    }
   
}
